package com.itheima.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import com.itheima.mapper.ReportMapper;
import com.itheima.pojo.*;
import com.itheima.service.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ReportServiceImpl implements ReportService {
    private final ReportMapper reportMapper;

    @Override
    public SetMealDateVo getSetmealReport() {
        List<SetmealReportItem> items = reportMapper.getSetmealReportItems();

        // 提取套餐名称列表
        List<String> setmealNames = items.stream()
                .map(SetmealReportItem::getName)
                .collect(Collectors.toList());

        // 构建 setmealCount 数组
        List<Map<String, Object>> setmealCountList = items.stream()
                .map(item -> {
                    Map<String, Object> countMap = new HashMap<>();
                    countMap.put("name", item.getName());
                    countMap.put("value", item.getValue());
                    return countMap;
                })
                .collect(Collectors.toList());

        return new SetMealDateVo(setmealNames, setmealCountList);
    }

    @Override
    public MemberDateVo getMemberReport() {
        List<MemberReportItem> items = reportMapper.getMemberReportItems();

        // 提取月份列表
        List<String> months = items.stream()
                .map(MemberReportItem::getMonth)
                .collect(Collectors.toList());

        // 提取会员数量列表
        List<Integer> memberCounts = items.stream()
                .map(MemberReportItem::getMemberCount)
                .collect(Collectors.toList());

        return new MemberDateVo(months, memberCounts);
    }

    @Override
    public ImportEntity getBusinessReport() {
        ImportEntity report = reportMapper.getBusinessReport();

        // 获取热门套餐数据
        List<SetmealReportItem> setmealItems = reportMapper.getSetmealReportItems();
        log.info("Setmeal Report Items: {}", setmealItems);
        int total = setmealItems.stream().mapToInt(SetmealReportItem::getValue).sum();

        // 转换为HotSetmeal对象
        List<ImportEntity.HotSetmeal> hotSetmeals = setmealItems.stream()
                .map(item -> new ImportEntity.HotSetmeal(
                        total > 0 ? (double) item.getValue() / total : 0,
                        item.getName(),
                        item.getValue()
                ))
                .collect(Collectors.toList());
        log.info("Hot Setmeals: {}", hotSetmeals);
        report.setHotSetmeal(hotSetmeals);
        return report;
    }

    @Override
    public void exportBusinessReport(HttpServletResponse response) {
        ImportEntity entity = reportMapper.getBusinessReport();

        // 获取热门套餐数据
        List<SetmealReportItem> setmealItems = reportMapper.getSetmealReportItems();
        int total = setmealItems.stream().mapToInt(SetmealReportItem::getValue).sum();

        // 转换为HotSetmeal对象
        List<ImportEntity.HotSetmeal> hotSetmeals = setmealItems.stream()
                .map(item -> new ImportEntity.HotSetmeal(
                        total > 0 ? (double) item.getValue() / total : 0,
                        item.getName(),
                        item.getValue()
                ))
                .collect(Collectors.toList());

        // 手动组装 map，hotSetmeal 必须是 List<HotSetmeal>
        Map<String, Object> map = new HashMap<>();
        map.put("reportDate", entity.getReportDate());
        map.put("todayNewMember", entity.getTodayNewMember());
        map.put("totalMember", entity.getTotalMember());
        map.put("thisWeekNewMember", entity.getThisWeekNewMember());
        map.put("thisMonthNewMember", entity.getThisMonthNewMember());
        map.put("todayOrderNumber", entity.getTodayOrderNumber());
        map.put("thisWeekOrderNumber", entity.getThisWeekOrderNumber());
        map.put("thisMonthOrderNumber", entity.getThisMonthOrderNumber());
        map.put("todayVisitsNumber", entity.getTodayVisitsNumber());
        map.put("thisWeekVisitsNumber", entity.getThisWeekVisitsNumber());
        map.put("thisMonthVisitsNumber", entity.getThisMonthVisitsNumber());
        map.put("hotSetmeal", hotSetmeals);

        // 日志输出每个热门套餐的类型，确保全是HotSetmeal对象
        for (Object o : hotSetmeals) {
            System.out.println("hotSetmeal item type: " + o.getClass() + ", value: " + o);
        }

        TemplateExportParams params = new TemplateExportParams("templates/report_template.xlsx", 0);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        responseWorkbook(response, workbook, "运营数据统计.xlsx");
    }

    /**
     * 导出 Excel
     *
     * @param response
     * @param workbook
     * @param fileName
     */
    private static void responseWorkbook(HttpServletResponse response, Workbook workbook, String fileName) {
        try {
            response.setHeader("Content-disposition", "attachment;" + "filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream; charset=UTF-8");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}